﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Net.Mail;
using System.Globalization;
using System.Configuration;
using System.Security.Cryptography;
using System.Web.Mvc;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text.RegularExpressions;

namespace SDT.Lib.Common
{
    public static class Utils
    {
        public static bool IsNullOrEmpty(string s)
        {
            return (s == null || s.Trim().Length == 0);
        }

        /// <summary>
        /// Author: Takamaru Nguyen.
        /// Date: 03/08/2011.
        /// </summary>
        public static bool IsDocument(this string str, string doc)
        {
            if (string.IsNullOrEmpty(str))
                return false;
            if (string.IsNullOrEmpty(doc))
                return true;

            int lastIndex = str.LastIndexOf(".");
            return str.Substring(lastIndex, str.Length - lastIndex).Contains(doc);
        }
        public static int ParseInt(string s)
        {
            try
            {
                return Int32.Parse(s);
            }
            catch
            {
                return -1;
            }
        }
        public static int ParseInt(string s, int defaultvalue)
        {
            try
            {
                return Int32.Parse(s);
            }
            catch
            {
                return defaultvalue;
            }
        }
        public static int ParseInt(object s)
        {
            try
            {
                return Int32.Parse(s.ToString());
            }
            catch
            {
                return -1;
            }
        }


        public static void SendMail(string to, string from, string subject, string body)
        {
            /// Using default Smtp config (config in Web.config)
            SmtpClient client = new SmtpClient();
            client.EnableSsl = true;

            /// Mail details
            MailMessage msg = new MailMessage();

            try
            {
                msg.From = new MailAddress(from, "contact@sdt.vn");
                msg.To.Add(to);
                msg.SubjectEncoding = System.Text.Encoding.UTF8;
                msg.Subject = subject;
                msg.IsBodyHtml = true;
                msg.BodyEncoding = System.Text.Encoding.UTF8;
                msg.Body = body;
                msg.Priority = MailPriority.Normal;

                /// Enable one of the following method.
                client.Send(msg);
            }
            catch (Exception exp)
            {
                /// Throw exception to higher tier
                throw exp;
            }
        }
        public static DateTime ParseDateTime(string s, CultureInfo culture)
        {
            try
            {
                return DateTime.Parse(s, culture);
            }
            catch
            {
                return DateTime.Now;
            }
        }
        public static Decimal ParseDecimal(string s)
        {
            try
            {
                return Decimal.Parse(s);
            }
            catch
            {
                return 0;
            }
        }
        public static Decimal ParseDecimal(object s)
        {
            try
            {
                return Decimal.Parse(s.ToString());
            }
            catch
            {
                return 0;
            }
        }
        public static Double ParseDouble(object s)
        {
            try
            {
                return Double.Parse(s.ToString());
            }
            catch
            {
                return 0;
            }
        }
        public static string EnCryptPassword(string strEncrypt)
        {
            byte[] hashedDataBytes;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(strEncrypt);
            UTF8Encoding encoder = new UTF8Encoding();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            hashedDataBytes = md5.ComputeHash(encoder.GetBytes(strEncrypt));
            md5.Clear();

            TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider();
            tdesProvider.Key = hashedDataBytes;
            tdesProvider.Mode = CipherMode.ECB;
            tdesProvider.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdesProvider.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdesProvider.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        public static string DownloadDocument(int docId, string fileName)
        {
            string basePath = ConfigurationSettings.AppSettings["SiteBaseUrl"];// HttpContext.Current.Server.MapPath("/Uploads/");// ConfigurationSettings.AppSettings["SiteBasePath"];
            string path = basePath + "Files/";
            path += "doc_" + docId.ToString() + fileName.Substring(fileName.LastIndexOf('.'));
            return path;
        }
       
        /// <summary>
        /// Convert from string with structor to dictionary
        /// </summary>
        /// <param name="strInput">Format input: strKey1:value1[separator]strKey2:value2</param>
        /// <param name="separator">dash separator</param>
        /// <returns>Dictionary contain key and value</returns>
        public static Dictionary<object, object> StringToDictionary(string strInput, string separator)
        {
            var dict = new Dictionary<object, object>();
            string[] stringList = strInput.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (stringList != null && stringList.Length > 0)
                foreach (var str in stringList)
                {
                    var obj = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    dict.Add(obj[0].Trim(), obj[1].Trim());
                }
            return dict;
        }
        public static Dictionary<int, string> StringToDictionaryIntString(string strInput, string separator)
        {
            var dict = new Dictionary<int, string>();
            string[] stringList = strInput.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (stringList != null && stringList.Length > 0)
                foreach (var str in stringList)
                {
                    var obj = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    dict.Add(int.Parse(obj[0].Trim()), obj[1].Trim());
                }
            return dict;
        }
        public static IList<SelectListItem> GetSelectListItemInConfig(string strInput, string separator, int selectedValue)
        {
            var l = Utils.StringToDictionaryIntString(strInput, separator);
            IList<SelectListItem> list = new List<SelectListItem>();
            foreach (var item in l) {
                SelectListItem s = new SelectListItem();
                s.Text = item.Value;
                s.Value =""+ item.Key;
                s.Selected = item.Key == selectedValue ? true : false;
                list.Add(s);
            }
            return list;
        }
        public static List<int> GetListKeyInConfig(string strInput, string separator)
        {
            var l = Utils.StringToDictionaryIntString(strInput, separator);
            List<int> key=new List<int>();
            var txtValue=string.Empty;
            foreach (var item in l)
            {
                key.Add(item.Key);
            }
            return key;
        }
        public static string StringFormatPrecision(int intPrecision)
        {
            string precision = "{0:#,##0.";
            for (int i = 0; i < intPrecision; i++)
            {
                precision += "0";
            }
            precision += "}";
            return precision;
        }
        public static string DownloadFile(string fileName, string inFolderID, string inFolder, string rootUrl)
        {
            var path = rootUrl + "Uploads/" + inFolder + "/Files/" + inFolderID + "_" + fileName;
            return path;
        }
        public static string DownloadDocument(string fileName, string inFolderID, string inFolder, string rootUrl)
        {
            var path = rootUrl + "Documents/" + inFolder + "/"+inFolderID +"/"+ fileName;
            return path;
        }
        public static void DeleteFile(string fileName, string inFolderID, string inFolder, string rootPath)
        {
            string path = rootPath +"\\\\Documents\\\\"+inFolder+"\\\\"+inFolderID+ "\\\\" + fileName;
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }
        public static void DeleteInFolder(string inFolderID, string inFolder, string rootPath)
        {
            string path = rootPath + "\\\\Documents\\\\" + inFolder + "\\\\" + inFolderID;
            if (Directory.Exists(path))
                Directory.Delete(path, true);
        }
        public static Image CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
        {
            System.Drawing.Bitmap bmpOut = null;
            try
            {

                System.Drawing.Image loBMP = System.Drawing.Image.FromFile(lcFilename);
                ImageFormat loFormat = loBMP.RawFormat;
                decimal lnRatio;
                int lnNewWidth = 0;
                int lnNewHeight = 0;
                //*** If the image is smaller than a thumbnail just return it

                if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
                    return loBMP;
                if (loBMP.Width > loBMP.Height)
                {

                    lnRatio = (decimal)lnWidth / loBMP.Width;
                    lnNewWidth = lnWidth;
                    decimal lnTemp = loBMP.Height * lnRatio;
                    lnNewHeight = (int)lnTemp;
                }
                else
                {

                    lnRatio = (decimal)lnHeight / loBMP.Height;
                    lnNewHeight = lnHeight;
                    decimal lnTemp = loBMP.Width * lnRatio;
                    lnNewWidth = (int)lnTemp;
                }

                bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
                Graphics g = Graphics.FromImage(bmpOut);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
                g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
                loBMP.Dispose();
            }
            catch
            {
                return null;
            }
            return bmpOut;

        }
        public static Image CreateThumbnail(string lcFilename, int lnWidth, int lnHeight, string pathLogo)
        {
            System.Drawing.Bitmap bmpOut = null;
            try
            {

                System.Drawing.Image loBMP = System.Drawing.Image.FromFile(lcFilename);
                ImageFormat loFormat = loBMP.RawFormat;
                decimal lnRatio;
                int lnNewWidth = 0;
                int lnNewHeight = 0;
                //*** If the image is smaller than a thumbnail just return it

                if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
                    return loBMP;
                if (loBMP.Width > loBMP.Height)
                {

                    lnRatio = (decimal)lnWidth / loBMP.Width;
                    lnNewWidth = lnWidth;
                    decimal lnTemp = loBMP.Height * lnRatio;
                    lnNewHeight = (int)lnTemp;
                }
                else
                {

                    lnRatio = (decimal)lnHeight / loBMP.Height;
                    lnNewHeight = lnHeight;
                    decimal lnTemp = loBMP.Width * lnRatio;
                    lnNewWidth = (int)lnTemp;
                }

                bmpOut = new Bitmap(lnNewWidth, lnNewHeight);               
                Bitmap logo = new Bitmap(pathLogo);
                if (logo != null) {
                    string watermark = "muaqua.vn";
                    loBMP = WaterMarkToImage(loBMP, watermark);
                    Graphics g = Graphics.FromImage(bmpOut);
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
                    g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
                }
                else
                {
                    Graphics g = Graphics.FromImage(bmpOut);
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
                    g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
                }
                loBMP.Dispose();
            }
            catch
            {
                return null;
            }
            return bmpOut;

        }
        public static System.Drawing.Image WaterMarkToImage(Image bmp, string watermark)
        {
            Graphics graphicsObject;
            int x, y;
            try
            {
                //create graphics object from bitmap
                graphicsObject = Graphics.FromImage(bmp);
            }
            catch (Exception e)
            {

                Bitmap bmpNew = new Bitmap(bmp.Width, bmp.Height);
                graphicsObject = Graphics.FromImage(bmpNew);

                graphicsObject.DrawImage(bmp, new Rectangle(0, 0, bmpNew.Width, bmpNew.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);

                bmp = bmpNew;
            }

            int startsize = (bmp.Width / watermark.Length);//get the font size with respect to length of the string

            //x and y cordinates to draw a string
            x = 10;
            y = bmp.Height / 2;

            //System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat(StringFormatFlags.DirectionVertical); -> draws a vertical string for watermark
            System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat(StringFormatFlags.NoWrap);

            //drawing string on Image
            graphicsObject.DrawString(watermark, new Font("Verdana", startsize, FontStyle.Bold), new SolidBrush(Color.FromArgb(60, 255, 255, 255)), x, y, drawFormat);

            //return a water marked image
            return (bmp);
        }
        //public static Bitmap WaterMarkToImage(string ImagePath, string watermark)
        //{
        //    Bitmap bmp;
        //    bmp = new Bitmap(ImagePath);
        //    Graphics graphicsObject;
        //    int x, y;
        //    try
        //    {
        //        //create graphics object from bitmap
        //        graphicsObject = Graphics.FromImage(bmp);
        //    }
        //    catch (Exception e)
        //    {

        //        Bitmap bmpNew = new Bitmap(bmp.Width, bmp.Height);
        //        graphicsObject = Graphics.FromImage(bmpNew);

        //        graphicsObject.DrawImage(bmp, new Rectangle(0, 0, bmpNew.Width, bmpNew.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);

        //        bmp = bmpNew;
        //    }
        //    var font = new Font("Tahoma", 24F, FontStyle.Bold);
        //    //x and y cordinates to draw a string
        //    x =10;
        //    y = bmp.Height/2;

        //    //System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat(StringFormatFlags.DirectionVertical); -> draws a vertical string for watermark
        //    System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat(StringFormatFlags.NoWrap);

        //    //drawing string on Image
        //    graphicsObject.DrawString(watermark, font, new SolidBrush(Color.FromArgb(60, 255, 255, 255)), x, y, drawFormat);

        //    //return a water marked image
        //    return (bmp);
        //}
        public static System.Drawing.Image ImageCrop(System.Drawing.Image imgPhoto, int Width, int Height, AnchorPosition Anchor)
        {

            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)Width / (float)sourceWidth);
            nPercentH = ((float)Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                switch (Anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = (int)(Height - (sourceHeight * nPercent));
                        break;
                    default:
                        destY = (int)((Height - (sourceHeight * nPercent)) / 2);
                        break;
                }
            }
            else
            {
                nPercent = nPercentH;
                switch (Anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = (int)(Width - (sourceWidth * nPercent));
                        break;
                    default:
                        destX = (int)((Width - (sourceWidth * nPercent)) / 2);
                        break;
                }

            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(Width, Height);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                imgPhoto.VerticalResolution);
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
            grPhoto.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.GammaCorrected;
            grPhoto.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            grPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);
            grPhoto.Dispose();
            return bmPhoto;
        }
        
        public static string GetThumbFullPath(int artId, string imgPath, int width, int height, string baseUrl)
        {
            string path = string.Empty;
            if (imgPath != null && imgPath != string.Empty)
            {
                path = baseUrl + string.Format("thumb/art_{0}_{1}_", width, height) + artId.ToString() + imgPath.Substring(imgPath.LastIndexOf('.'));
            }
            return path;
        }
        public static string GetThumbFullPath(int artId, string imgPath, int width, int height, string baseUrl, string pathFile)
        {
            string path = string.Empty;
            if (File.Exists(pathFile))
            {
                if (imgPath != null && imgPath != string.Empty)
                {
                    path = baseUrl + string.Format("thumb/art_{0}_{1}_", width, height) + artId.ToString() + imgPath.Substring(imgPath.LastIndexOf('.'));
                }                
                //string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
                //Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
                //path = r.Replace(path, "");
                path = path.Replace(" ", "");
                return path;
            }
            else
            {
                var http="http://";
                var link= baseUrl.Replace(http,string.Empty);
                return http + link.Substring(0, link.IndexOf("/")) + Globals.DefaultLogo;
            }
           
        }
        public static string GetSiteThumbFullPath(int artId, string imgPath, int width, int height, string basePath)
        {
            string path = string.Empty;
           //string basePath = ConfigurationSettings.AppSettings["SiteBasePath"];// HttpContext.Current.Server.MapPath("/Uploads/");// ConfigurationSettings.AppSettings["SiteBasePath"];
            if (imgPath != null && imgPath != string.Empty)
            {
                path = basePath + string.Format("thumb\\art_{0}_{1}_", width, height) + artId.ToString() + imgPath.Substring(imgPath.LastIndexOf('.'));
            }
            return path;
        }
        public static string GetSitePathImgNotReSize(int artId, string imgPath, string basePath)
        {
            string path = string.Empty;
            //string basePath = ConfigurationSettings.AppSettings["SiteBasePath"];// HttpContext.Current.Server.MapPath("/Uploads/");// ConfigurationSettings.AppSettings["SiteBasePath"];
            if (imgPath != null && imgPath != string.Empty)
            {
                path = basePath + artId.ToString() + "_" + imgPath;
            }
            return path;
        }
        public static string GenThumbnail(int artId, int width, int height, string fileName,string basePath,string baseUrl)
        {
            try
            {
                string fileNameGen = GetSiteThumbFullPath(artId, fileName, width, height, basePath);
                string fileNotGen = GetSitePathImgNotReSize(artId, fileName, basePath);
                if (File.Exists(fileNameGen))
                {
                    if (File.GetLastWriteTime(fileNotGen) > File.GetLastWriteTime(fileNameGen))
                    {
                        System.Drawing.Image bmThumb = CreateThumbnail(fileNotGen, width, height);
                        SaveThumbnail(bmThumb, width, height, fileNameGen);
                    }
                }
                else
                {
                    System.Drawing.Image bmThumb = CreateThumbnail(fileNotGen, width, height);
                    SaveThumbnail(bmThumb, width, height, fileNameGen);

                }
                return GetThumbFullPath(artId, fileName, width, height, baseUrl, fileNameGen);
            }
            catch (Exception exp)
            {
                return string.Empty;
            }

        }
        
        public static void SaveThumbnail(System.Drawing.Image bmThumb, int width, int height, string filePath)
        {
            if (bmThumb != null)
            {
                if (!Directory.Exists(filePath.Substring(0, filePath.LastIndexOf("\\"))))
                {
                    // If it doesn't then we just create it before going any further
                    Directory.CreateDirectory(filePath.Substring(0, filePath.LastIndexOf("\\")));
                }
                bmThumb.Save(filePath, bmThumb.RawFormat);
                bmThumb.Dispose();
            }
        }
        public static string[] GetImageInFolder(int inFolder, string rootPath, string rootUrl)
        {
            try
            {
                string path = rootPath + "\\\\" + inFolder.ToString() + "\\\\";
                string[] files = Directory.Exists(path) ? Directory.GetFiles(path) : new string[0];
                if (files.Length == 0) return new string[0];

                string thumbOfFile = string.Empty;
                string notResizeOfFile = string.Empty;
                if (files.Length > 0)
                {
                    string[] listfile = new string[files.Length];
                    int index = 0;
                    foreach (string file in files)
                    {
                        FileInfo fileinfo = new FileInfo(file);
                        listfile[index] = GetImageFullPathInFolder(inFolder.ToString(), fileinfo.Name, rootUrl);
                        index++;
                    }
                    return listfile;
                }
                else return new string[0];
            }
            catch (Exception exp)
            {
                return new string[0];
            }

        }
        public static string GetImageFullPathInFolder(string InFolder, string fileName, string rooUrl)
        {
            string path = string.Empty;
            if (fileName != null && fileName != string.Empty)
            {
                path = rooUrl.LastIndexOf("/") == rooUrl.Length - 1 ? rooUrl + string.Format("{0}/{1}", InFolder, fileName) :
                    rooUrl + string.Format("/{0}/{1}", InFolder, fileName);
            }
            return path;
        }
        public static string[] GenThumbnailInFolder(int inFolder, int width, int height, string SiteRootPath, string SiteRootUrl)
        {
            try
            {
                var path = string.Format("{0}{1}", SiteRootPath, inFolder.ToString());
                var thumbpath = string.Format("{0}{1}{2}", SiteRootPath, "Thumb\\", inFolder.ToString());

                if (!Directory.Exists(thumbpath))
                {
                    // If it doesn't then we just create it before going any further
                    Directory.CreateDirectory(thumbpath);
                }
                string[] files = Directory.Exists(path) ? Directory.GetFiles(path) : new string[0];
                if (files.Length <= 0) return new string[0];
                string thumbOfFile = string.Empty;
                string notResizeOfFile = string.Empty;
                if (files.Length > 0)
                {
                    string[] listfile = new string[files.Length];
                    int index = 0;
                    foreach (string file in files)
                    {
                        if (CheckImageFile(file))
                        {
                            FileInfo fileinfo = new FileInfo(file);
                            thumbOfFile = thumbpath + "\\\\" + string.Format("{0}_{1}_{2}", width, height, fileinfo.Name);
                            notResizeOfFile = path + "\\\\" + fileinfo.Name;
                            if (File.Exists(thumbOfFile))
                            {
                                if (File.GetLastWriteTime(notResizeOfFile) > File.GetLastWriteTime(thumbOfFile))
                                {
                                    System.Drawing.Image bmThumb = CreateThumbnail(notResizeOfFile, width, height);
                                    SaveThumbnail(bmThumb, width, height, thumbOfFile);
                                }
                            }
                            else
                            {
                                System.Drawing.Image bmThumb = CreateThumbnail(notResizeOfFile, width, height);
                                SaveThumbnail(bmThumb, width, height, thumbOfFile);

                            }
                            listfile[index] = GetThumbFullPathInFolder(inFolder.ToString(), fileinfo.Name, width, height, SiteRootUrl);
                            index++;
                        }
                    }
                    return listfile;

                }
                else return new string[0];
            }
            catch (Exception exp)
            {
                return new string[0];
            }

        }
        public static string[] GenThumbnailInFolder(int inFolder, int width, int height, string SiteRootPath, string SiteRootUrl, string logoPath)
        {
            try
            {
                var path = string.Format("{0}{1}", SiteRootPath, inFolder.ToString());
                var thumbpath = string.Format("{0}{1}{2}", SiteRootPath, "Thumb\\", inFolder.ToString());

                if (!Directory.Exists(thumbpath))
                {
                    // If it doesn't then we just create it before going any further
                    Directory.CreateDirectory(thumbpath);
                }
                string[] files = Directory.Exists(path) ? Directory.GetFiles(path) : new string[0];
                if (files.Length <= 0) return new string[0];
                string thumbOfFile = string.Empty;
                string notResizeOfFile = string.Empty;
                if (files.Length > 0)
                {
                    string[] listfile = new string[files.Length];
                    int index = 0;
                    foreach (string file in files)
                    {
                        if (CheckImageFile(file))
                        {
                            FileInfo fileinfo = new FileInfo(file);
                            thumbOfFile = thumbpath + "\\\\" + string.Format("{0}_{1}_{2}", width, height, fileinfo.Name);
                            notResizeOfFile = path + "\\\\" + fileinfo.Name;
                            if (File.Exists(thumbOfFile))
                            {
                                if (File.GetLastWriteTime(notResizeOfFile) > File.GetLastWriteTime(thumbOfFile))
                                {
                                    System.Drawing.Image bmThumb = CreateThumbnail(notResizeOfFile, width, height, logoPath);
                                    SaveThumbnail(bmThumb, width, height, thumbOfFile);
                                }
                            }
                            else
                            {
                                System.Drawing.Image bmThumb = CreateThumbnail(notResizeOfFile, width, height, logoPath);
                                SaveThumbnail(bmThumb, width, height, thumbOfFile);

                            }
                            listfile[index] = GetThumbFullPathInFolder(inFolder.ToString(), fileinfo.Name, width, height, SiteRootUrl);
                            index++;
                        }
                    }
                    return listfile;

                }
                else return new string[0];
            }
            catch (Exception exp)
            {
                return new string[0];
            }
        }
        public static bool CheckImageFile(string path)
        {
            
            switch (Path.GetExtension(path).ToLower())
            {
                case ".bmp": return true;
                case ".gif": return true;
                case ".jpg": return true;
                case ".png": return true;
            }
            return false;
        }

        public static string GetThumbFullPathInFolder(string InFolder, string fileName,int width, int height, string SiteRootUrl)
        {
            string path = string.Empty;
            if (fileName != null && fileName != string.Empty)
            {
                path = SiteRootUrl + "Thumb/" + InFolder + "/" + width + "_" + height + "_" + fileName;
            }
            return path;
        }
        public static string ReadNumber(double number)
        {
            var b = new StringBuilder();
            if (number <= 0) return "0";
            if (number < Math.Pow(10, 6))
            {
                b.Append(number);
                //b.Append(" nghìn");
                return b.ToString();
            }
            if (Math.Pow(10, 6) <= number && number < Math.Pow(10, 9))
            {
                b.Append(Math.Round(number / Math.Pow(10, 6), 2));
                b.Append(" triệu");
                return b.ToString();
            }
            if (number >= Math.Pow(10, 9))
            {
                b.Append(Math.Round(number / Math.Pow(10, 9), 2));
                b.Append(" tỷ");
                return b.ToString();
            }
            return null;
        }
        public static string GetIcon(string fileName, string SiteRootUrl)
        {
            var path = SiteRootUrl != string.Empty ? SiteRootUrl + "icon-16-" : "/images/ftc/icon-16-";
            var extent = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
            switch (extent) { 
                case "pdf":
                    path = path + "pdf.png";
                    break;
                case "xlsx":
                case "xls":
                    path = path + "excel.png";
                    break;
                case "doc":
                case "docx":
                    path = path + "word.png";
                    break;
                case "rar":
                case "zip":
                    path = path + "zip.png";
                    break;
                default:
                    path = path + "zip.png";
                    break;
            }
            return path;
        }
        public static List<SelectListItem> ListGioiTinh()
        {
            var data = new List<SelectListItem>();
            var list = new SelectListItem()
            {
                Text = "Nam",
                Value = "Nam"

            };
            var list1 = new SelectListItem()
            {
                Text = "Nữ",
                Value = "Nữ"

            };
            data.Add(list);
            data.Add(list1);
            return data;

        }
        //lay huong         
        public static List<SelectListItem> ListHuongNha()
        {
            string[] dsHuongNha = { "Tây Bắc", "Bắc", "Đông Bắc", "Tây", "Đông", "Tây Nam", "Nam", "Đông Nam" };
            var data = new List<SelectListItem>();

            foreach (var item in dsHuongNha)
            {
                var list = new SelectListItem()
                {
                    Value = item.Trim().ToString(),
                    Text = item.Trim().ToString()
                };
                data.Add(list);
            }
            return data;

        }
        public static List<SelectListItem> ListNam()
        {
            var data = new List<SelectListItem>();



            int namhientai = DateTime.Now.Year;
            var listnam = new List<int>();
            for (int i = namhientai; i < namhientai + 40; i++)
            {
                var list = new SelectListItem()
                {
                    Value = i.ToString(),
                    Text = i.ToString()

                };
                data.Add(list);
            }

            return data;
        }
        public static List<SelectListItem> ListStatus()
        {
            var data = new List<SelectListItem>();
            for (int i = 0; i <=1; i++)
            {
                var list = new SelectListItem()
                {
                    Value = i.ToString(),
                    Text = i==0? "Không":"Có"

                };
                data.Add(list);
            }
            return data;
        }
        public static string GetRandomPassword(int numChars)
        {
            var gui = Guid.NewGuid().ToString().Replace("-","").Substring(0,numChars);
            return gui;
        }
        public static int DateDiffInDays(DateTime fromDate, DateTime toDate)
        {
            return toDate.Subtract(fromDate).Days;
        }
        public static int DateDiffInDays(DateTime? fromDate)
        {
            return fromDate.HasValue ? DateTime.Now.Subtract(fromDate.Value).Days : 0;
        }
        public static int GetDaysBetweenDates(DateTime? fromDate, DateTime? toDate)
        {
            int countDown = 0;
            if (toDate.HasValue && fromDate.HasValue && toDate.Value > fromDate.Value)
            {
                TimeSpan t = toDate.Value - fromDate.Value;
                countDown = t.Days > 0 ? t.Days : 0;
            }
            return countDown;
        }
        public static string GetCountDownDate(DateTime? fromDate, DateTime? toDate)
        {
            if (toDate.HasValue && fromDate.HasValue && toDate.Value>fromDate.Value)
            { 
                TimeSpan t = toDate.Value - fromDate.Value;
                string countDown = string.Format("<b>{0}</b> Ngày, <b>{1}</b> Giờ, <b>{2}</b> Phút", t.Days, t.Hours, t.Minutes);
                return countDown;
            }
            return string.Empty;
        }
        private static string NumberToText(int number)
        {
            string sR = "";
            switch (number)
            {
                case 0: sR = "không"; break;
                case 1: sR = "một"; break;
                case 2: sR = "hai"; break;
                case 3: sR = "ba"; break;
                case 4: sR = "bốn"; break;
                case 5: sR = "năm"; break;
                case 6: sR = "sáu"; break;
                case 7: sR = "bảy"; break;
                case 8: sR = "tám"; break;
                case 9: sR = "chín"; break;
                default: sR = ""; break;
            }
            return sR;
        }
        private static String ConvertMoney(string Number)
        {
            String sNumber = "";
            int len = Number.Length;
            if (len == 1)
            {
                int iNu = Utils.ParseInt("" + Number[0]);
                sNumber += NumberToText(iNu);
            }
            else if (len == 2)
            {
                int iChuc = Utils.ParseInt("" + Number[0]);
                int iDV = Utils.ParseInt("" + Number[1]);
                if (iChuc == 1)
                {
                    if (iDV > 0)
                    {
                        sNumber += "Mười " + NumberToText(iDV);
                    }
                    else
                    {
                        sNumber += "Mười ";
                    }
                }
                else
                {
                    sNumber += iDV > 0 ? NumberToText(iChuc) + " mươi " + NumberToText(iDV) : NumberToText(iChuc) + " mươi ";
                }
            }
            else
            {
                int iTram = Utils.ParseInt("" + Number[0]);
                int iChuc = Utils.ParseInt("" + Number[1]);
                int iDV = Utils.ParseInt("" + Number[2]);

                if (iChuc == 0)
                {
                    if (iDV > 0)
                    {
                        sNumber += NumberToText(iTram) + " trăm linh " + NumberToText(iDV);
                    }
                    else
                    {
                        sNumber += iTram > 0 ? NumberToText(iTram) + " trăm" : "";
                    }
                }
                else if (iChuc == 1)
                {
                    if (iDV > 0)
                    {
                        sNumber += NumberToText(iTram) + " trăm mười " + NumberToText(iDV);
                    }
                    else
                    {
                        sNumber += NumberToText(iTram) + " trăm mười ";
                    }
                }
                else
                {
                    if (iDV > 0)
                    {
                        sNumber += NumberToText(iTram) + " trăm " + NumberToText(iChuc) + " mươi " + NumberToText(iDV);
                    }
                    else
                    {
                        sNumber += NumberToText(iTram) + " trăm " + NumberToText(iChuc) + " mươi ";
                    }
                }
            }
            return sNumber;
        }
        public static long ParseLong(decimal s)
        {
            try
            {
                return (long)(s);
            }
            catch
            {
                return -1;
            }
        }
        //Phương thức chuyển đổi
        public static string TranlateMoney(decimal? dNumber)
        {

            String sNumber = string.Empty;
            sNumber = dNumber.HasValue ? "" + Utils.ParseLong(dNumber.Value) : "0";
            String sR = "";
            String sR1 = "";
            String sR2 = "";
            String sR3 = "";
            String sR4 = "";

            int seq = 0;
            int k = 1;
            for (int i = sNumber.Length; i >= 0; i--)
            {
                if (seq == 3)
                {
                    String subStr = sNumber.Substring(i, seq);
                    if (k == 1)
                    {
                        sR = ConvertMoney(subStr) + " đồng";
                    }
                    else if (k == 2)
                    {
                        sR1 = ConvertMoney(subStr) + " nghìn ";
                    }
                    else if (k == 3)
                    {
                        sR2 = ConvertMoney(subStr) + " triệu ";
                    }
                    else
                    {
                        sR3 = ConvertMoney(subStr) + " tỷ ";
                    }
                    seq = 0;
                    k++;
                }
                seq++;
            }
            if (seq > 1)
            {
                String subStr = sNumber.Substring(0, seq - 1);
                if (k == 1)
                {
                    sR = ConvertMoney(subStr) + " đồng";
                }
                else if (k == 2)
                {
                    sR1 = ConvertMoney(subStr) + " nghìn ";
                }
                else if (k == 3)
                {
                    sR2 = ConvertMoney(subStr) + " triệu ";
                }
                else
                {
                    sR3 = ConvertMoney(subStr) + " tỷ ";
                }
            }
            //seq
            sR4 = sR3 + sR2 + sR1 + sR;
            if (sR1 + sR == "không trăm nghìn không trăm đồng") sR4 = sR3 + sR2 + " đồng chẵn";
            return sR4;
        }    
    }
}
